import {message} from 'antd';
// import message from '../../_antd1.11.2/message'
import isEmpty from 'lodash/isEmpty'
import isArray from 'lodash/isArray'
import forEach from 'lodash/forEach'
import isEqual from './isEqual'
import * as format from './format'
import './index.less'
require("./jquery.poshytip.js")

// 定义组件的key（server端生成）
const KEY_1 = 'd51f298d-5f51-4a4b-b25a-0a0e0e978c1d'; // 普通input
const KEY_2 = 'c1f5bfcf-d6dd-4b20-b461-55ba4bcfc831'; // 类型
const KEY_3 = '169b6798-a098-408b-a685-b79a64d5804a'; // 工作流
const KEY_4 = 'c3b220db-0926-4a28-88ab-56545e4c9770'; // 紧急程度,处理状态,流程状态,节点类型  单选组件
const KEY_5 = '575e1d52-d6e2-41d6-b2fd-18f8390dbc49'; // 创建人   creatertype   0为员工传参createrid，1为客户传参createrid2
const KEY_6 = '76370661-6d2e-415b-afb3-0fa419d4e12c'; // 创建人部门
const KEY_7 = '0eaf61b7-9f96-4bf7-960d-ea89997e2d82';  // 创建人分部
const KEY_8 = 'e0ea2e01-6d46-4b74-bb5b-6a386e072c44'; // 创建日期,接收日期
const KEY_9 = '04dda747-af1a-446b-99ad-90ead5eb357e'; // 未操作者, 人力资源
const KEY_10 = 'd71cbaa2-50ef-4c01-b0c6-76abf468058b'; // 相关文档
const KEY_11 = '094035a2-e0d5-434f-a40d-ce7dd2261eba'; // 相关客户
const KEY_12 = 'cafcd71c-43e1-4f6c-a9b0-77a37c62720c'; // 相关项目

import WeaInput from '../wea-input'
import WeaTextarea from '../wea-textarea'
import WeaProjectInput from '../wea-project-input'
import WeaDocInput from '../wea-doc-input'
import WeaCrmInput from '../wea-crm-input'
import WeaWfInput from '../wea-wf-input'
import WeaWtInput from '../wea-wt-input'
import WeaHrmInput from '../wea-hrm-input'
import WeaDepInput from '../wea-dep-input'
import WeaComInput from '../wea-com-input'
import WeaDateGroup from '../wea-date-group'
import WeaSelect from '../wea-select'
import WeaBrowser from '../wea-browser'
import WeaCheckbox from '../wea-checkbox'
import WeaSelectGroup from '../wea-select-group'
import WeaScope from '../wea-scope'
import WeaDatePicker from '../wea-date-picker'
import WeaTimePicker from '../wea-time-picker'

//switch 部分处理
const formatSelectOptions = (options) => {
    let results = [];
    forEach(options, (option) => {
        results.push({
            value: option.key,
            name: option.showname
        })
    })
    return results;
}

const getSelectDefaultValue = (options) => {
    let value = '';
    forEach(options, (option) => {
        if(option.selected){
            value = option.key;
        }
    })
    return value;
}

//fetch 部分处理
const server = window.server||"";

const getFd = (values) => {
    let fd = "";
    for(let p in values) {
        if(p == 'jsonstr' && typeof values[p] === 'object'){
            fd += p+"="+JSON.stringify(values[p]).replace(/\\/g,'')+"&";
        }else{
            fd += p+"="+encodeURIComponent(values[p])+"&";
        }
    }
    return fd;
}

const getFetchParams = (method,params)=>{
    let obj = {
        method:method,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
            'X-Requested-With':'XMLHttpRequest'
        },
    };
    if(server=="") {
        obj.credentials = "include";
    }
    if(!isEmpty(params) && method.toUpperCase() !== 'GET') {
        obj.body = getFd(params);
    }
    return obj;
}

const checkReject = (obj)=>{
    let isFalse = false;
    if(obj.errorCode && obj.errorCode==="001") { //session异常，如果有路由就强制跳转
        message.error("session过期，请重新登陆！",5);
        //跳转登陆页
        if(weaHistory) {
            weaHistory.push("/");
        }
        else if(weaWfHistory) {
            window.href.location = "/wui/index.jsp";
        }
        isFalse = true;
    }
    else if(typeof obj.status !== 'undefined' && (!obj.status || obj.status ==='false')) {
        message.error("接口业务逻辑错误："+ obj.error,5);
        isFalse = true;
    }
    return isFalse;
}

const trim = (s) => {
    return s.replace(/(^\s*)|(\s*$)/g,'');
}

const tools = {
    ls:{
        set:function(key,val) {
            if(typeof val==="object") {
                window.localStorage[key] = JSON.stringify(val);
            } else {
                window.localStorage[key] = val;
            }
        },
        getStr:function(key) {
            return window.localStorage[key] || "";
        },
        getJSONObj:function(key) {
            if(!window.localStorage[key]) return null;
            return JSON.parse(window.localStorage[key]);
        }
    },
    ss:{
        set:function(key,val) {
            if(typeof val==="object") {
                window.sessionStorage[key] = JSON.stringify(val);
            } else {
                window.sessionStorage[key] = val;
            }
        },
        getStr:function(key) {
            return window.sessionStorage[key] || "";
        },
        getJSONObj:function(key) {
            if(!window.sessionStorage[key]) return null;
            return JSON.parse(window.sessionStorage[key]);
        }
    },
    tryCatch:function(React, ErrorHandler, handlerOptions) {
        if (!React || !React.Component) {
            throw new Error('arguments[0] for react-try-catch-render does not look like React.');
        }
        if (typeof ErrorHandler !== 'function') {
            throw new Error('arguments[1] for react-try-catch-render does not look like a function.');
        }
        /**
         * Implementation of the try/catch wrapper
         * @param  {[React.Component]} component The ES6 React.Component
         */
        return function wrapWithTryCatch(Component) {
            const originalRender = Component.prototype.render;

            Component.prototype.render = function tryRender() {
                try {
                    return originalRender.apply(this, arguments);
                } catch (err) {
                    // Log an error
                    window.console && console.error("errorLog:",err);
                    if(ErrorHandler.prototype && ErrorHandler.prototype.render) {
                        return React.createElement(ErrorHandler, handlerOptions);
                    }
                    // ErrorHandler is at least a valid function
                    return ErrorHandler(err);
                }
            };
            return Component;
        };
    },
    callApi:(url, method = 'GET', params = {}, type = 'json') => {
    	if(typeof localStorage.access_token === 'string' && localStorage.access_token !== ''){
        	params.access_token = localStorage.access_token
        }
        url = `${server}${url}`;
        if (method.toUpperCase() === 'GET' && !isEmpty(params)) {
            let c = '?';
            if (/\?/.test(url)) c = '&';
            url = `${url}${c}${getFd(params)}`;
        }
        if (method.toUpperCase() === 'GET' && !/__random__/.test(url)) {
            let c = '?';
            if (/\?/.test(url)) c = '&';
            url += c + "__random__="+new Date().getTime();
        }
        return new Promise((resolve,reject) => {
            fetch(url, getFetchParams(method, params)).then(function(response) {
                let data = "";
                if(type==="json")
                    data = response.json();
                else
                    data = response.text();
                return data
            }).then(data => {
                if(checkReject(data)) {
                    console && console.error(`${url} fetch 请求异常: ${data.error || 'error'}`);
                    reject(`${url} fetch 请求异常: ${data.error || 'error'}`);
                }
                else {
                    resolve(data);
                }
            }).catch(function(ex) {
                console && console.error(`${url} fetch 数据处理异常: ${ex}`);
                reject(`${url} fetch 数据处理异常: ${ex}`);
            });
        });
    },
    checkSession:(nextState, replace ,callback)=>{
        //console.log("in checkSession!");
        /*setTimeout(()=>{
            console.log("listDoing async!");
            replace({pathname:"/"}); //强制登出或者报错
            callback();
        },1000);

        */
        callback();
    },
    switchComponent: (props, key, FieldProps, field = {}, layout) => {
        const {getFieldProps} = props.form;
        //  根据key类型返回相对应的组件
        switch (key) {
            case KEY_1:
                return (<WeaInput {...getFieldProps(FieldProps[0])}/>)
                // return (<WeaBrowser
                // tabs={[{key:'1',name:'全部',dataParams:{list:'1', isLoadSubDepartment: '1'},selected: true},{key:'2',name:'我的收藏', selected:false}]}
                // isSingle={false}
                // title='请求多选' type={164} {...getFieldProps(FieldProps[0])}/>)
            case KEY_2:
                return (<WeaWtInput {...getFieldProps(FieldProps[0])} getPopupContainer={() => (layout || document.body)}/>)
            case KEY_3:
                return (<WeaWfInput {...getFieldProps(FieldProps[0])} getPopupContainer={() => (layout || document.body)} />)
            case KEY_4:
                return (<WeaSelect options = {field.options}
                    {...getFieldProps(FieldProps[0],{
                        initialValue: getSelectDefaultValue(field.options)
                    })} getPopupContainer={() => (layout || document.body)} />)
            case KEY_5:
                return (<WeaHrmInput {...getFieldProps(FieldProps[1])} oldUrl conditionURL = {`/api/workflow/browser01/condition/1`} getPopupContainer={() => (layout || document.body)} />)
            case KEY_6:
                return (<WeaDepInput {...getFieldProps(FieldProps[0])} getPopupContainer={() => (layout || document.body)} />)
            case KEY_7:
                return (<WeaComInput {...getFieldProps(FieldProps[0])} getPopupContainer={() => (layout || document.body)} />)
            case KEY_8:
                return (<WeaDateGroup {...getFieldProps(FieldProps[0],{
                        initialValue: getSelectDefaultValue(field.options)
                    })} datas={formatSelectOptions(field.options)} form={props.form} domkey={FieldProps}
                     getPopupContainer={() => (layout || document.body)} />)
            case KEY_9:
                return (<WeaHrmInput {...getFieldProps(FieldProps[0])} oldUrl conditionURL = {`/api/workflow/browser01/condition/1`} getPopupContainer={() => (layout || document.body)} />)
            case KEY_10:
                return (<WeaDocInput {...getFieldProps(FieldProps[0])} getPopupContainer={() => (layout || document.body)} />)
            case KEY_11:
                return (<WeaCrmInput {...getFieldProps(FieldProps[0])} getPopupContainer={() => (layout || document.body)} />)
            case KEY_12:
                return (<WeaProjectInput {...getFieldProps(FieldProps[0])} getPopupContainer={() => (layout || document.body)} />)
            default:
                return (<WeaInput {...getFieldProps(FieldProps[0])}/>);
        }
    },
    isComponentHide(field) {
        let hide = false;
        if (field) {
            let ct = field.conditionType.toUpperCase();
            let viewAttr = field.viewAttr;
            if (ct == 'BROWSER') viewAttr = field.browserConditionParam.viewAttr;
            hide = viewAttr == -1; // -1 隐藏
        }
        return hide;
    },
    getComponent(conditionType = 'input', browserConditionParam, domkey, props, field, hasUnderline = false){
        // console.log('=========================',conditionType,browserConditionParam);
        let ct = conditionType.toUpperCase();
        const {getFieldProps} = props.form;
        if (ct == 'INPUT'){
            return (<WeaInput {...getFieldProps(domkey[0],{initialValue: field.value})}
                    length={field.length}
                    viewAttr={field.viewAttr}
                    hasBorder={!hasUnderline}
                    underline={hasUnderline}
                />);
        }
        if (ct == 'TEXTAREA'){
            return (<WeaTextarea {...getFieldProps(domkey[0],{initialValue: field.value})}
                    length={field.length}
                    minRows={field.minRows ? field.minRows: 2}
                    maxRows={field.maxRows}
                    viewAttr={field.viewAttr}
                />);
        }
        if(ct == 'SELECT'){
            return (
                <WeaSelect
                    {...getFieldProps(domkey[0], {
                        initialValue: getSelectDefaultValue(field.options)
                    })}
                    options= {field.options}
                    viewAttr={field.viewAttr}
                    hasBorder={!hasUnderline}
                    underline={hasUnderline}
                />
            );
        }
        if(ct == 'BROWSER'){
            // console.log('BROWSER');
            const  showDropMenu = browserConditionParam.type=='4' || browserConditionParam.type=='164';//部门分部显示维度菜单
            // console.log('=========',showDropMenu);
            return (
                <WeaBrowser isAdSearch
                    hasBorder={!hasUnderline}
                    underline={hasUnderline}
                    {...browserConditionParam} showDropMenu={showDropMenu}  {...getFieldProps(domkey[0])} layout={document.body}/>
            );
        }
        if(ct == 'DATE'){
            // console.log('DATE===field',field);{...getFieldProps(domkey[0],{initialValue: '0'})}
            let value = '0'
            if (!isEmpty(field.value)) {
                const {setFieldsValue} = props.form;
                value = field.value[domkey[0]];
            }
            let datas = [
                {value:'0',name:'全部'},
                {value:'1',name:'今天'},
                {value:'2',name:'本周'},
                {value:'3',name:'本月'},
                {value:'4',name:'本季'},
                {value:'5',name:'本年'},
                {value:'7',name:'上个月'},
                {value:'8',name:'上一年'},
                {value:'6',name:'指定日期范围'}];
            if (!isEmpty(field.options)) {
                datas = [];
                field.options.forEach(o => {
                    datas.push({
                        value: o.key,
                        name: o.showname,
                    })
                })
            }
            return (
                <WeaDateGroup
                    {...getFieldProps(domkey[0], {initialValue: value})}
                    datas={datas}
                    form={props.form}
                    values={field.value}
                    domkey={domkey}
                    viewAttr={field.viewAttr}
                />
            );
        }
        if(ct == 'CHECKBOX'){
            return (
                <WeaCheckbox
                    {...getFieldProps(domkey[0],{initialValue: field.value})}
                    viewAttr={field.viewAttr}
                />
            );
        }
        if(ct == 'SELECT_LINKAGE'){
            return (
                <WeaSelectGroup
                    {...getFieldProps(domkey[0], {initialValue: this.getSelectDefaultValue(field.options)})}
                    selectWidth={field.selectWidth}
                    options={field.options}
                    selectLinkageDatas={field.selectLinkageDatas}
                    form={props.form}
                    domkey={domkey}
                    viewAttr={field.viewAttr}
                />
            );
        }
        if(ct == 'SCOPE'){
            return (
                <WeaScope
                    {...getFieldProps(domkey[0])}
                    startValue={field.startValue}
                    endValue={field.endValue}
                    min={field.min}
                    max={field.max}
                    form={props.form}
                    domkey={domkey}
                    step={field.step}
                    viewAttr={field.viewAttr}
                />
            );
        }
        if(ct == 'DATEPICKER'){
            return (
                <WeaDatePicker
                    {...getFieldProps(domkey[0], {initialValue: field.value})}
                    formatPattern={field.formatPattern || 2}
                    viewAttr={field.viewAttr}
                    hasBorder={!hasUnderline}
                    underline={hasUnderline}
                />
            );
        }
        if(ct == 'TIMEPICKER'){
            return (
                <WeaTimePicker
                    {...getFieldProps(domkey[0], {initialValue: field.value})}
                    formatPattern={field.formatPattern || 3}
                    viewAttr={field.viewAttr}
                    hasBorder={!hasUnderline}
                    underline={hasUnderline}
                />
            );
        }
    },
    getFd: getFd,
    isEqual: isEqual,
    getSelectDefaultValue: getSelectDefaultValue,
    formatDate: format.formatToDate,
    formatTime: format.formatToTime,
    getParamsByConditions(conditions) {
        let params = {};
        !isEmpty(conditions) && conditions.forEach((c) => {
            const conditionType = c.conditionType;
            if(conditionType == 'INPUT'){
                if (c.value) params[c.domkey[0]] = c.value;
            }
            if(conditionType == 'SELECT'){
                let value = getSelectDefaultValue(c.options);
                if (value) params[c.domkey[0]] = value;
            }
            if(conditionType == 'BROWSER'){
                if (!isEmpty(c.browserConditionParam)) {
                    const replacesDatas = c.browserConditionParam.replaceDatas;
                    let values = [], value;
                    !isEmpty(replacesDatas) && replacesDatas.forEach((d) => {
                        values.push(d.id);
                    })
                    value = values.join(',');
                    if (value) params[c.domkey[0]] = value;
                }
            }
            if(conditionType == 'DATE'){
                if (!isEmpty(c.value) && isArray(c.domkey)) {
                    c.domkey.forEach(d => {
                        if (c.value[d]) {
                            params[d] = c.value[d];
                        }
                    })
                }
            }
        })
        return params;
    },
    getTextWidth(str) {
        let width = 0;
        if (str) {
            for (var i = 0; i < str.length; i++) {
                //如果是汉字
                if (str.charCodeAt(i) > 255) {
                    width += 14;
                }
                else {
                    width += 7;
                }
            }
        }
        return width;
    },
    getZindex(page = 'home', defaultIndex = 99) {
        const key = `${page}ZINDEX`;
        const cache = this.ss.getStr(key);
        const zindex = cache? Number(cache) + 1: defaultIndex;
        this.ss.set(key, zindex);
        return zindex;
    },
    tooltip(dom, params = {}) { // http://vadikom.com/demos/poshytip/
        if (!dom || !jQuery) return;
        if (!(dom instanceof jQuery)) {
            dom = jQuery(dom);
        }
        if (typeof params === 'string') return dom.poshytip(params);
        const config = {...{
            className: 'tip-yellow',
            alignX: 'right',
            alignY: 'center',
            fade: false,
            slide: false,
            offsetX: 0
        } , ...params}
        dom.poshytip(config);
    },
    isWeekendDay(str) {
        let bool = false;
        if (str) {
            let dt = new Date(str);
            if (dt.getDay() == 0 || dt.getDay() == 6) {
                bool = true;
            }
        }
        return bool;
    },
    isBelowIE9() {
      return navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion.split(";")[1].replace(/[ ]/g, "").replace("MSIE","")) <= 9;
    }
}

const render = (_idArray, _nameArray, _jobtitleArray, __x, __y) => {
    var browgroupHtml = "";
    var _i;
    for (_i=0; _i<_idArray.length; _i++) {
        var className=(_i%2==1?"ac_even":"ac_odd");
        var displaycss = _i > 4 ? " display:none; " : "";
        var resdetailinfohtml = "<span style='display:inline-block;width:80px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;'><a href=javaScript:openhrm(" + _idArray[_i] + "); onclick='pointerXY(event);' style='overflow: hidden;white-space: nowrap;text-overflow: ellipsis;' title='" + _nameArray[_i] + "'>" + _nameArray[_i] + "</a></span>";
        resdetailinfohtml += "<span style='float:right;display:inline-block;width:130px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;' title='" + _jobtitleArray[_i] + "'>" + _jobtitleArray[_i] + "</span>";

        browgroupHtml += '<li class="'+className+'" _id="'+_idArray[_i]+'" style=\'' + displaycss + '\'>' + resdetailinfohtml +'</li>';



        if (_i > 4 && _i == _idArray.length-1) {
            browgroupHtml += '<li class="'+className+'" title="显示全部" style="text-align:center;" onclick="showallCrmsdetail(this);">显示全部</li>';
        }
    }

    if(!!browgroupHtml){
        var autoCompleteDiv = jQuery("<div id='__brow__detaildiv' class='wea-hrmgroup-wrapper' style=\"position:absolute;width:245px;z-index:1099;left:" + __x + "px;top:" + __y + "px;\"></div>");
        var autoCompleteDiv_html = jQuery("<div class=\"arrowsblock\"><img src=\"/images/ecology8/workflow/multres/arrows_2_wev8.png\" width=\"22px\" height=\"22px\"></div>"
            + "<div class='ac_results' style='margin-top:20px;background:#fff;z-index:9;'><ul>"+browgroupHtml+"</ul></div>"
        );
        var mask = jQuery("<div id='__brow__detaildiv_mask' onclick='closeCrmsDetail();' style=\"position:fixed; top:0;left:0;right:0;bottom:0; z-index:1098;\"></div>");
        autoCompleteDiv.append(autoCompleteDiv_html);
        //autoCompleteDiv_html.addClass("ac_results");
        jQuery("body").append(mask).append(autoCompleteDiv);
    }

}

window.showCrmsDetail = (e, params = {}) => {
    closeCrmsDetail();
    const target = jQuery(e.target);
    let x = target.offset().left - (245 - target.width())/2 ;
    let y = target.offset().top + 15;
    render(params.ids, params.names, params.jobtitles, x, y);
}

window.closeCrmsDetail = () => {
    jQuery("#__brow__detaildiv_mask").remove();
    jQuery("#__brow__detaildiv").remove();
}

window.showallCrmsdetail = (ele) => {
    var target = jQuery(ele);
    var parentDiv = target.closest("div");
    parentDiv.css({
        "height":parentDiv.height() + "px",
        "overflow" : "auto"
    });

    //parentDiv.perfectScrollbar({horizrailenabled:false,zindex:1000});

    var othli = target.parent().children().not(":visible");
    othli.show();
    target.hide();
}

export default tools;